<template>
  <main>
    <van-tabs v-model="active" @click="handleTab" color="#FF5722">
      <van-tab v-for="(item, index) in tabList" :key="index" :title="item.name">
      </van-tab>
    </van-tabs>
    <van-loading v-if="loading"/>
    <van-empty :description="`暂无订单`" v-else-if="empty"/>
    <van-list
      v-else
      ref="orderlist"
      v-model="mode_loading"
      :finished="finished"
      :finished-text="footText"
    >
      <li class="order-list" v-for="(item, index) in orderList">
        <div class="order-id">
          <p class="title">
            {{ OrderTypeMap[item.order_type] }}
            <span class="create_at">
              <i class="iconfont icon-_time-copy"></i>
              {{ item.created_at }}
            </span>
          </p>
          <span :class="'status_' + item.order_status">
            {{ (item.order_status == '2' && item.order_type == '2') ? '审核中' : statusMap[item.order_status] }}
          </span>
        </div>
        <div class="order-main" @click="goDetail(item)">
          <img src="~assets/images/logo1.jpg" alt="" class="logo" v-if="item.order_type == '1'">
          <img src="~assets/images/logo2.jpg" alt="" class="logo" v-else>
          <div>
            <p v-if="item.order_type == '1'">
              油品：<span class="gas_label">{{ item.gas_type }}</span>
            </p>
            <p>加油金额：<span class="rmb">{{ item.order_amount / 100 }}</span></p>
            <p> 实付：<span class="rmb amount">{{ Number(item.amount) / 100 }}</span></p>
          </div>
          <span class="detail_icon">
            <i class="iconfont icon-arrow"></i>
          </span>
        </div>
        <div class="status-btn" v-if="item.order_status == 1">
          <div class="count-time">
            <i class="iconfont icon-shijian"></i>
            <van-count-down :time="item.count * 1000" />
          </div>
          <div>
            <van-button 
              round size="small" 
              type="default"
              @click="cannelOrder(item)">
              取消订单
            </van-button>
            <van-button 
              round size="small" 
              color="linear-gradient(to right, #ff6034, #ee0a24)" 
              @click="goPayMoney(item)">
              去付款
            </van-button>
          </div>
        </div>
      </li>
    </van-list>
  </main>
</template>

<script>
import Vue from 'vue'
import { Dialog, Toast } from 'vant';
import { mapActions, mapGetters } from 'vuex'
import { OrderStatusMap, OrderTabList, OrderTypeMap } from 'utils/enum'
import * as Api from 'api'

export default {
  data() {
    return {
      OrderTypeMap: OrderTypeMap,
      loading: true,
      mode_loading: false,
      empty: false,
      finished: false,
      footText: '没有更多了',
      active: 0,
      current_page: 1,
      statusMap: OrderStatusMap,
      tabList: OrderTabList,
      orderList: [],
    }
  },
  computed: {
    ...mapGetters([
      'orderTabIndex',
      'orderType'
    ]),
  },
  created() {
    this.$emit('showTabMenu', false);
    this.active = this.orderTabIndex
    this.getOrderList()
  },
  mounted () {
    window.onscroll = () => {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //变量windowHeight是可视区的高度
      var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      //滚动条到底部的条件
      if(scrollTop + windowHeight == scrollHeight){
        this.onLoad()
      } 
    }
  },
  methods: {
    ...mapActions([
      'OrderTabIndex',
      'SetOrderType'
    ]),
    initData() {
      this.orderList = []
      this.current_page = 1
      this.finished = false;
      this.footText = '没有更多了'
      this.empty = false
      this.loading = true
    },
    getOrderList () {
      let params = {
        page: this.current_page,
        order_status: this.tabList[this.active].status,
        order_type: this.orderType
      }
      // this.finished = true;
      Api.OrderList(params).then(res => {
        this.loading = false
        if (res.data.total == 0) {
          this.empty = true
        }
        if (res.data.current_page >= res.data.last_page) {
          this.finished = true
        }
        this.orderList = this.orderList.concat(res.data.data)
      })
    },
    handleTab(index) {
      this.OrderTabIndex(index)
      if (this.tabList[index].order_type) {
        this.SetOrderType(this.tabList[index].order_type)
      } else {
        this.SetOrderType('')
      }
      this.initData()
      this.getOrderList()
    },
    goPayMoney(item) {
      Api.againPay({order_id: item.order_id}).then(res => {
        this.goPayment(JSON.parse(res.data.payInfo), res.data.merchOrderNo)
      })
    },
    onBridgeReady(info, order_id) {
      WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": info.appId,
        //公众号名称，由商户传入     
        "timeStamp": info.timeStamp,
        //时间戳，自1970年以来的秒数     
        "nonceStr": info.nonceStr,
        //随机串     
        "package": info.package,
        "signType": "RSA",
        //微信签名方式：     
        "paySign": info.paySign //微信签名 
      }, (res) => {
        console.log(res, '支付回调');
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          Api.queryPayment({order_id: order_id}).then(data => {
            console.log(data, '查询支付结果');
          })
        }
      });
    },
    goPayment(info, order_id) {
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      } else {
        this.onBridgeReady(info, order_id);
      }
    },
    cannelOrder(item) {
      Dialog.confirm({
        title: '提示',
        message: '是否取消订单？',
      }).then(() => {
        Api.CancelOrder({'order_id': item.order_id}).then(res => {
          Toast('订单已取消！')
          this.initData()
          this.getOrderList()
        }).catch(() => {
        })
      }).catch(() => {
        // on cancel
      });
    },
    // 加载分页
    onLoad() {
      if (this.finished) return false
      this.current_page ++
      this.getOrderList()
    },
    goDetail(item) {
      this.$router.push({path: `/orderDetail/${item.order_type}/${item.order_id}`})
    }
  }
}
</script>

<style scoped lang="less">
main{
  background: #f2f4f5;
}
.van-loading{
  background: #fff;
  padding: 20px;
  text-align: center;
}
.van-empty{
  background: #fff;
}
/deep/ .van-tabs--line .van-tabs__wrap{
  margin-bottom: 10px;
}
.order-list{
  background: #fff;
  font-size: 14px;
  margin-bottom: 10px;
  list-style: none;
  &:last-of-type{
    margin-bottom: 0;
  }
  .order-id{
    display: flex;
    justify-content: space-between;
    padding: 8px 20px;
    border-bottom: 1px solid #f5f5f5;
    .title{
      font-weight: bold;
      font-size: 15px;
      .create_at{
        font-size: 14px;
        font-weight: 500;
        color: #777;
        margin-left: 10px;
        i{
          font-size: 14px;
        }
      }
    }
  }
  .logo{
    width: 80px;
  }
  .order-main{
    display: grid;
    grid-template-columns: 80px auto 80px;
    gap: 20px;
    padding: 10px 20px;
    .amount{
      font-size: 20px;
      font-weight: bold;
      color: #FF5722;
    }
    .gas_label{
      background: #FFC107;
      color: #fff;
      border-radius: 4px;
      padding: 2px 5px;
      font-size: 12px;
      transform: scale(0.8);
      display: inline-block;
    }
    .detail_icon{
      align-self: center;
      justify-self: end;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 24px;
      height: 24px;
      color: #aaa;
      border-radius: 50%;
      border: 1px solid #ddd;
      i{
        font-size: 14px;
      }
    }
  }
}

.status-btn{
  border-top: 1px solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 20px;
  button{
    margin-left: 20px;
    padding: 0 15px;
  }
}
.count-time{
  display: flex;
  align-items: center;
  color: #F44336;
  i{
    margin-right: 5px;
    font-size: 14px;
  }
  .van-count-down{
    color: #F44336;
    line-height: normal;
  }
}
.flex-between{
  align-items: flex-end;
}
</style>